from flask import jsonify
import time
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from sqlalchemy.exc import OperationalError


def wait_db(db_uri, retries=5, delay=5):
    """等待数据库连接成功，重试指定次数"""
    engine = create_engine(db_uri)
    for i in range(retries):
        try:
            # 尝试连接数据库
            with engine.connect() as conn:
                print("数据库连接成功")
                return True
        except OperationalError:
            print(f"数据库连接失败，正在重试 {i + 1}/{retries}...")
            time.sleep(delay)
    return False


class JsonResponse:
    @staticmethod  # 简化类，不用再写__init__
    def success(message, data=None):
        response = {
            "status": "success",
            "msg": message,
            "data": data
        }
        return jsonify(response)

    @staticmethod
    def error(message, data=None):
        response = {
            "status": "error",
            "msg": message,
            "data": data
        }
        return jsonify(response)


class Info:
    def __init__(self, msg, data=None):
        self.msg = msg
        self.data = data
